package com.iflytek.cosmo.ocr.support.license.client.v1;

import java.time.Duration;
import java.time.Instant;

import com.iflytek.cosmo.ocr.common.enums.LicenseEnum;
import com.iflytek.cosmo.ocr.support.license.LicenseVersion;
import com.iflytek.cosmo.ocr.support.license.client.ClientLicense;
import lombok.Data;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/2/5
 */
@Data
public class ClientLicenseV1 extends ClientLicense {

    /** 授权类型 */
    private LicenseEnum type;

    /** 有效时间 最长68年, 精确到分钟
     * 示例: "P2D":2天, "P2DT3H4M":2天3小时4分钟 "P6H3M":6小时3分钟
     * 格式见: {@link java.time.Duration#parse} */
    private String validity;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());
        sb.append(type.getCode());
        sb.append(FIELD_SEPARATOR);
        sb.append(validity);
        return sb.toString();
    }

    public ClientLicenseV1() {
        this.version = LicenseVersion.V1.getCode();
    }

    public ClientLicenseV1(Instant createTime, int count, int index) {
        this.version = LicenseVersion.V1.getCode();
        this.createTime = createTime;
        this.count = count;
        this.index = index;
    }

    public ClientLicenseV1(String license) {
        super(license);
        String versionDetail = license.substring(license.indexOf(SUBCLASS_SEPARATOR) + 1);
        int separatorIndex = versionDetail.indexOf(FIELD_SEPARATOR);
        String typeStr = versionDetail.substring(0, separatorIndex);
        this.validity = versionDetail.substring(separatorIndex + 1);
        this.type = LicenseEnum.getByCode(typeStr);

        if (validity != null && validity.trim().length() != 0) {
            try {
                Duration.parse(validity);
            }
            catch (Exception e) {
                throw new RuntimeException("有效期格式错误: "+ this.validity, e);
            }
        }
    }

    public static void main(String[] args) {
        ClientLicenseV1 v1 = new ClientLicenseV1();
        v1.setCreateTime(Instant.now());
        v1.setCount(30);
        v1.setIndex(7);

        v1.setType(LicenseEnum.FORMAL);
        v1.setValidity("P36500D");
        System.out.println(v1);
    }

    public void setValidity(String validity) {
        Duration duration = null;
        try {
            duration = Duration.parse(validity);
        }
        catch (Exception e) {
            throw new RuntimeException("有效期格式错误: " + duration, e);
        }

        if (duration == null) {
            throw new RuntimeException("有效期格式错误: " + duration);
        }
        this.validity = validity;
    }

    /** 获取有效期, 单位: 分钟 */
    public int getValidityMin() {
        Duration duration = Duration.parse(validity);
        return Math.toIntExact(duration.toMinutes());
    }
}
